(function(window){
  'use strict';

  var App = window.App || {};
  var $ = window.jQuery;

  function CheckList(selector) {
    if(!selector){
      throw new Error('No selector provided');
    }

    this.$element = $(selector);
    if(this.$element.length === 0) {
      throw new Error('Could not find element with selector: ' + selector);
    }
  }

  function Row(coffeeOrder) {
    var $div = $('<div></div>',{
      'data-coffee-order': 'checkbox',
      'class': 'checkbox'
    });

    var $label = $('<label></label>');
    var $checkbox = $('<input></input>', {
      type: 'checkbox',
      value: coffeeOrder.emailAddress,
    });

    var description = coffeeOrder.size + ' ';
    if(coffeeOrder.flavor){
      description += coffeeOrder.flavor + ' ';
    }

    description += coffeeOrder.coffee + ', ';
    description += ' (' + coffeeOrder.emailAddress + ')';
    description += ' [' + coffeeOrder.strength + 'x]';

    $label.append($checkbox);
    $label.append(description);
    $div.append($label);

    this.$element = $div;
  }

  CheckList.prototype.addRow = function(coffeeOrder) {
    //移除匹配相应的邮箱地址已经有的行 (本项目 一个邮箱只能有一个订单)
    this.removeRow(coffeeOrder.emailAddress)
    //使用 咖啡 订单信息 创建一个新的Row实例
    var rowElement = new Row(coffeeOrder);
    //把新的Row实例的$element属性添加 到清单中
    this.$element.append(rowElement.$element);
  }

  CheckList.prototype.removeRow = function(email) {
    //链式操作  可以换行 写
    this.$element
                .find('[value="'+email+'"]')
                .closest('[data-coffee-order="checkbox"]')
                .remove();
  }

  CheckList.prototype.addClickHandler = function(fn){
    this.$element.on('click', 'input', function(event){
      var email = event.target.value;
      this.removeRow(email);
      fn(email);
    }.bind(this));
  }

  App.CheckList = CheckList;
  window.App = App;
})(window);
